#!/usr/bin/env python
# coding = utf-8

import configparser
import os
import sys
import boto3
import json
import time
import datetime
import xlsxwriter

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj,datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self,obj)



def security_group():
    workbook = xlsxwriter.Workbook("Security_group_inbound.xlsx")
    worksheet = workbook.add_worksheet("inbound")
#    vpc_message = vpc_info()
#    length = len(vpc_message)
    title = [u'SecurityGroupName', u'SecurityGroupID', u'VPC_ID', u'Protocol', u'Portrange', u'source']
    format_title = workbook.add_format()
    format_title.set_border(1)
    format_title.set_bg_color('#cccccc')

    format_text = workbook.add_format()
    format_text.set_border(1)

    worksheet.set_column('A:K',40)   #设置A到K列宽度20像素
    worksheet.write_row('A1',title,format_title)   #将title列表有A1开始横向写入，并且格式为format_title
    client = boto3.client('ec2')
    instance = client.describe_security_groups(
            )['SecurityGroups']

    if not instance:
        return None

    length = len(instance)
    From_dict = {}
    IpProtocol_dict = {}
    CidrIp_dict = {}
    No_IpPermissions = {}
    count = 1
    count1 = 2
    nums = len(From_dict)

    for i in range(length):
        attached_security_group_ids = []
        GroupName = instance[i]['GroupName']
        GroupId = instance[i]['GroupName']
        VpcId = instance[i]['VpcId']
        data = [GroupName, GroupId, VpcId]
#        worksheet.write_row('A'+str(count+i+1), data, format_text)

        attached_security_group_ids.append([GroupName, GroupId, VpcId])
        instance_id = instance[i]['IpPermissions']
#        instance_ip = instance[i]['IpPermissions']['IpRanges']
        lengthid = len(instance_id)
#        lengthip = len(instance_ip)
        if instance_id:
#            print(lengthid)

            for k in range(lengthid):
#                print(instance_id[k])
#                FromPort = instance_id[k]['FromPort']
#                ToPort = instance_id[k]['ToPort']
                if "FromPort" in instance_id[k].keys():
                    FromPort = instance_id[k]['FromPort']
                    ToPort = instance_id[k]['ToPort']
                    IpProtocol_dict.setdefault(GroupName, []).append(instance_id[k]['IpProtocol'])
#                    worksheet.write_row('D'+str(count+i+1), [instance_id[k]['IpProtocol']], format_text)
                    if FromPort == ToPort:
                        From_dict.setdefault(GroupName, []).append(FromPort)
                    else:
                        From_dict.setdefault(GroupName, []).append(str(FromPort)+'-'+str(ToPort))

                else:
                    From_dict.setdefault(GroupName, []).append('')
                    IpProtocol_dict.setdefault(GroupName, []).append('')

                if 'IpRanges' in instance_id[k].keys():
                    lengthip = len(instance_id[k]['IpRanges'])
#                    print(lengthip)
#                    if lengthip >= count:
                    for n in range(lengthip):
                        #print(instance_id[k]['IpRanges'][n]['CidrIp'])
                        CidrIp = instance_id[k]['IpRanges'][n]['CidrIp']
                        CidrIp_dict.setdefault(GroupName,[]).append(instance_id[k]['IpRanges'][n]['CidrIp'])
                        print(GroupName, GroupId, VpcId, FromPort, instance_id[k]['IpRanges'][n]['CidrIp'])
                        step = len(CidrIp)
                        data1 = [GroupName, GroupId, VpcId, FromPort, CidrIp]
                        worksheet.write_row('A'+str(count+i+1), data1, format_text)
                        count += step
                  #  else:
                  #      CidrIp_dict.setdefault(GroupName,[]).append(instance_id[k]['IpRanges'][n]['CidrIp'])
#                else:
#                    CidrIp_dict.setdefault(GroupName,[]).append(instance_id[k]['IpRanges'][n]['CidrIp'])
#                for k1 in From_dict:
                   # print(From_dict[k1])
                    #print(GroupName, GroupId, VpcId, FromPort, instance_id[k]['IpRanges'][n]['CidrIp'])
#                    worksheet.write_row('E'+str(count+i+1), From_dict[k1], format_text)

        else:
            #GroupId = []
#            attached_security_group_ids.append({GroupName: GroupId})
            print('')
#            print(attached_security_group_ids)



   # for v in nums:
    #   count1 = count1 + 1
    print(CidrIp_dict)
       #worksheet.write_row('E'+str(count1-1), From_dict[k1], format_text)
#    if GroupName in IpProtocol_dict
#    data2 = []
#    worksheet.write_row('D'+str(count+i+1), IpProtocol_dict, format_text)

#return GroupName, GroupId, VpcId, IpProtocol_dict, From_dict, CidrIp_dict

#    print(list(map(lambda args: args, From_dict)))
#def excel(GroupName, GroupId, VpcId, IpProtocol_dict, From_dict, CidrIp_dict):
#    workbook = xlsxwriter.Workbook("Security_group_inbound.xlsx")
#    worksheet = workbook.add_worksheet("inbound")
#    vpc_message = vpc_info()
#    length = len(vpc_message)
#    title = [u'SecurityGroupName', u'SecurityGroupID', u'VPC_ID', u'Protocol', u'Portrange', u'source']
#    format_title = workbook.add_format()
#    format_title.set_border(1)
#    format_title.set_bg_color('#cccccc')

#    format_text = workbook.add_format()
#    format_text.set_border(1)

#    worksheet.set_column('A:K',20)   #设置A到K列宽度20像素
#    worksheet.write_row('A1',title,format_title)   #将title列表有A1开始横向写入，并且格式为format_title
#    count = 2
#    data = ([GroupName, GroupId, VpcId, IpProtocol_dict, From_dict, CidrIp_dict])
#    worksheet.write_row('A'+str(count+i+1), [GroupName], format_text)
    workbook.close()



if __name__ == '__main__':
    security_group()


